# bootsmooth
# userhandlers.py

import web
import logging
import datetime

from bootsmooth import *
from models import Greeting

from google.appengine.ext import db

# example RESTful interface
class greeting:
	def GET(self, key):
	
		# get message by key
		try:
			obj = db.get(key)
			
			if obj:
				objData = obj._entity
				objData['key'] = str(obj.key())
				return utility.json_dump(objData)
			else:
				return utility.json_error('Could not get object')
		except Exception as e:
			return utility.json_error('Could not get object: ' + str(e))
			
	def POST(self, key=""):
		data = web.input()
		
		try:
			obj = Greeting()
			obj.message = data.message
			obj.datetime = datetime.datetime.now().strftime('%Y/%m/%d %H:%M')
			
			obj.save()
			return utility.json_dump(obj.toDict())
		except Exception as e:
			return utility.json_error('Could not save data: ' + str(e))
	
	def PUT(self, key):
		obj = db.get(key)
		
		if obj:
			try:
				obj.message = data.message
				obj.datetime = datetime.datetime.now().strftime('%Y/%m/%d %H:%M')
				obj.save()
				
				return utility.json_dump(obj.toDict())
				
			except Exception as e:
				return utility.json_error('Could not save data: ' + str(e))
		else:
			return utility.json_error('Could not get object')
	
	# Delete object from datastore
	def DELETE(self, key):
		try:
			i = db.get(key)
			db.delete(i)
			return utility.json_dump({'success': '1'});
		except Exception as e:
			logging.warning('Error: ' + str(e))
			return utility.json_error(str(e))

